
import React, { useEffect, useMemo, useState } from 'react'
import { Header, AlertTip } from 'src/components'
import { useSelector } from 'react-redux'
import { getcaptchas, exChangeHongbao } from 'src/api/getData'
import classNames from 'classnames'
import './index.scss'

const Exchange = () => {
    const { userInfo } = useSelector(state => state);
    const [showAlert, setShowAlert] = useState(false)
    const [alertText, setAlertText] = useState()
    const [exchangeCode, setExchangeCode] = useState()
    const [codeNumber, setCodeNumber] = useState('')
    const [captchaCodeImg, setCaptchaCodeImg] = useState()

    const status = useMemo(() => {
        let status = (/^\d+$/gi.test(exchangeCode)) && (/^\w{4}$/gi.test(codeNumber))
        return status;
    }, [exchangeCode, codeNumber])

    useEffect(() => {
        getCaptchaCode()
    }, [])
    //线上环境采用固定的图片，编译环境获取真实的验证码
    const getCaptchaCode = async () => {
        let res = await getcaptchas();
        setCaptchaCodeImg(res.code)
    }
    //兑换红包
    const exchange = async () => {
        if (status) {
            let res = await exChangeHongbao(userInfo.user_id, exchangeCode, codeNumber);
            //不成功则弹出提示框
            if (res.message) {
                getCaptchaCode();
                setShowAlert(true);
                setAlertText(res.message);
            }
        }
    }
    const onClose = () => {
        setShowAlert(false);
    }
    return <div className="page_benefit_exchange">
        <Header title="兑换红包" goBack></Header>
        <form className="exchange_code">
            <input type="text" placeholder="请输入兑换码" className="exchange_input"
                value={exchangeCode}
                onInput={(e) => setExchangeCode(e.target.value)}
            />
            <section className="input_container captcha_code_container">
                <input
                    type="text"
                    placeholder="验证码"
                    maxlength="4"
                    value={codeNumber}
                    onInput={(e) => setCodeNumber(e.target.value)}
                />
                <div className="img_change_img">
                    {captchaCodeImg && <img src={captchaCodeImg} alt="" />}
                    <div className="change_img" onClick={getCaptchaCode}>
                        <p>看不清</p>
                        <p>换一张</p>
                    </div>
                </div>
            </section>
        </form>
        <div onClick={exchange} className={classNames('determine', { active: status })}>兑换</div>
        {showAlert && <AlertTip onClose={onClose} alertText={alertText}></AlertTip>}
    </div>
}

export default Exchange